<template>
  <div class="search">
    <img class="downloadAppImgUrl" src="https://yanxuan.nosdn.127.net/static-union/16607924415e76bf.png?type=webp&imageView&thumbnail=750x0&quality=75" alt="">
    <van-search v-model="keyword" @focus="onFocus" @blur="onBlur" @update:model-value="onInputKwChange" show-action :placeholder="kwPlace" @search="onSearch" @cancel="onCancel" @clear="onClear" />
    <!-- 历史记录 -->
    <div v-show="!isSearching && !keywordTipsShow && historyKeywords.length" class="history">
      <div class="title">
        <span>历史记录</span>
        <van-icon @click="handleClearHistoryKeywords" name="delete-o" />
      </div>
      <div class="keywords">
        <van-tag @click="handleSearchByHistory(kw)" v-for="kw in historyKeywords"
          :key="kw"  plain type="primary">{{ kw }}</van-tag>
      </div>
    </div>
    <!-- 热门搜索 -->
    <div v-show="!isSearching && !keywordTipsShow" class="hot">
      <div class="title">
        <span>热门搜索</span>
      </div>
      <div class="keywords">
        <van-tag ref="searchInputRef" @click="handleSearchByHistory(kw.keyword)" :class="{ active: !!kw.highlight }" v-for="kw in hotKeywords"
          :key="kw.keyword" plain type="primary">{{ kw.keyword }}</van-tag>
      </div>
    </div>
    <!-- 搜索结果 -->
    <div v-show="isSearching && !keywordTipsShow" class="searchResult">
      <div class="options">
        <div class="option">
          综合
        </div>
        <div class="option">
          <span>价格</span>
          <div class="priceOrder">
            <van-icon name="arrow-up" size="10px" />
            <van-icon name="arrow-down" size="10px" />
          </div>
        </div>
        <div class="option">
          分类
        </div>
      </div> 
      <div class="goods_list">
        <div v-for="(goods, i) in directlyList" :key="i" class="goods_item" :style="{paddingRight: i % 2 == 0 ? '3px' : 0, paddingLeft: i % 2 == 1 ? '3px' : 0}">
          <van-image
            width="100%"
            heigh="100%"
            fit="cover"
            position="center"
            :src="goods.listPicUrl"
          />
          <div class="description">
            <img class="preLogo" src="https://yanxuan.nosdn.127.net/static-union/16698631101bcf18.png" alt="preLogo">
            {{ goods.name }}
          </div>
          <div class="price">
            ￥<span>12</span>{{ '.9' }}
          </div>
          <div v-if="goods.finalPriceInfoVO.banner" class="additional" :style="{backgroundColor: goods.finalPriceInfoVO.banner.title?'#ffe9eb':'#fff'}">
            <span class="title">{{goods.finalPriceInfoVO.banner.title || goods.finalPriceInfoVO.banner.content}}</span>
            <span v-show="goods.finalPriceInfoVO.banner.title" class="description">{{goods.finalPriceInfoVO.banner.content}}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 实时关键字 -->
    <div v-show="keywordTipsShow && keyword" class="keyword_tips">
      <div @click="handleSearchByHistory(kw); keywordTipsShow = false" v-for="kw in keyword_tips" class="tip_item">
        <span>{{kw}}</span>
        <van-icon name="arrow" />
      </div>
    </div>
  </div>
</template>

<script setup>
import request from '../../utils/request'
import { onMounted, ref, reactive } from 'vue'
import {reqGetSearchData, reqGetSearchAutoComplete} from '../../api/search/index'

// 热门搜索词 
const hotKeywords = ref([])
// 历史搜索词
const historyKeywords = ref(['毛巾'])

// 搜索词的placeholder列表
const kwPlace = ref('')
const kwPlaceList = ref([])
const getInitData = async () => {
  const res = await request('/xhr/search/init.json')
  hotKeywords.value = res.hotKeywordVOList
  kwPlaceList.value = res.defaultKeywords

  // 随机一个数，用来取关键字
  const randomIndex = Math.ceil(Math.random() * (kwPlaceList.value.length)) - 1
  kwPlace.value = kwPlaceList.value[randomIndex].keyword
}
// 页面挂载后
onMounted(() => {
  getInitData()

  // 渲染历史关键词记录
  historyKeywords.value = JSON.parse(localStorage.getItem('historyKeywords') || '[]')
})

// 搜索词
const keyword = ref('')

// 根据历史记录搜索
const handleSearchByHistory = (kw) => {
  keyword.value = kw
  
  // 发送搜索请求
  getSearchData()
}
// 搜索功能
const onSearch = () => {
  getSearchData()
}
// 取消搜索：
const onCancel = () => {
  // 隐藏关键词提示框
  keywordTipsShow.value = false
}
const searchInputRef = ref(null)
const onClear = () => {
  // searchInputRef.value.focus()
}

// 搜索
// 搜索历史存入本地存储
// const historyKeywords

const directlyList = ref([]) // 搜索结果
const categoryL1List = ref([]) // 搜索返回的分类
const getSearchData = async () => {
  const searchParams = {
    "__timestamp": Date.now()+'',
    "keyword": keyword.value,
    "sortType": "0",
    "descSorted": "false",
    "categoryId": "0",
    "matchType": "0",
    "floorPrice": "-1",
    "upperPrice": "-1",
    "size": "40",
    "itemId": "0",
    "stillSearch": "false",
    "searchWordSource": "1",
    "needPopWindow": "true",
    "_stat_search": "userhand"
  }
  // 提交搜索请求
  const res = await reqGetSearchData(searchParams)
  directlyList.value = res.directlyList
  categoryL1List.value = res.categoryL1List

  // 展示搜索结果
  isSearching.value = true

  // 存入本地
  // 防止重复
  if(historyKeywords.value.includes(keyword.value)) return
  historyKeywords.value.push(keyword.value)
  localStorage.setItem('historyKeywords', JSON.stringify(historyKeywords.value))
}

// 控制 历史搜索/热门搜索/搜索结果 的 显示 or 隐藏
const isSearching = ref(false)

// 获取实时关键字
const keyword_tips = ref([])
const onInputKwChange = async (kw) => {
  // 搜索框内容变化时，实时提示搜索关键词
  keyword_tips.value = await reqGetSearchAutoComplete(kw)

  // 显示实时搜索结果展示
  keywordTipsShow.value = true
  // 关键词为空，则隐藏关键词提示框
  !kw && (keywordTipsShow.value = false)
}
// 控制实时关键字搜索结果的 显示 or 隐藏
const keywordTipsShow = ref(false)

const onFocus = async() => {
  if(keyword.value) {
    keyword_tips.value = await reqGetSearchAutoComplete(keyword.value)
    isSearching.value = false
    keywordTipsShow.value = true
  } else {
    isSearching.value = false
    keywordTipsShow.value = false
  }
}
const onBlur = () => {
  // isSearching.value = false
  // 
}
// 清空历史关键词
const handleClearHistoryKeywords = () => {
  historyKeywords.value = []
  localStorage.setItem('historyKeywords', JSON.stringify([]))
}
</script>

<style lang="less" scoped>
.van-tag {
  color: '#000';
  padding: 3px 6px
} 

.search {
  background-color: #eee;
  height: 100vh;

  &>* {
    background-color: #fff;
  } 
  .downloadAppImgUrl {
    width: 100%
  }
  .history {
    margin-bottom: .25rem;
  }

  .history,
  .hot {
    overflow: hidden;
    padding: 12px;

    .title {
      color: #bbb;
      font-size: 15px;
      margin-bottom: .4rem;
    }

    .van-icon {
      float: right;
      font-size: 0.5rem;
    }

    .keywords {
      line-height: 0;

      .van-tag {
        color: #000;
        margin-right: 0.35rem;
        margin-bottom: 0.35rem;
      }

      .active {
        color: red
      }
    }
  }

  .searchResult {
    font-size: .4rem;
    .options {
      display: flex;
      border-bottom: 1px solid #ccc;
      background-color: #fafafa;
      .option {
        text-align: center;
        flex: 1;
        height: 2.4em;
        line-height: 2.4em;

        .priceOrder {
          display: inline-block;
          display: inline-flex;
          flex-direction: column;
          vertical-align: middle;
          margin-left: 0.05rem;
        }
      }
    }
    .goods_list {
      display: flex;
      flex-wrap: wrap;
      padding: .2rem;
      .goods_item{
        box-sizing: border-box;
        width: 50%;
        margin-bottom: .6rem;
        :deep(.van-image) {
          width: calc(50vw - .2rem);
          height: calc(50vw - .2rem);
          border-radius: .2rem;
          img {
            border-radius: .2rem;
          }
        }
        .description {
          line-height: 1.4em;
          display: -webkit-box;
          overflow: hidden;
          text-overflow: ellipsis;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          .preLogo {
            width: 1.25em;
            vertical-align: middle;
          }
        }
        .price{
          font-weight: bold;
          font-size: .4rem;
          color: rgb(250, 30, 50);
          span {
            font-size: .6rem;
          }
        }
        .additional {
          display: flex;
          background-color: #ffe9eb;
          margin-top: .3rem;
          color: #fa1e32;
          font-size: .3rem;
          border-radius: .3rem;
          .title, .description {
            border-radius: .3rem;
            padding: 2px .2rem;
          }
          .title {
            background-color: rgb(250, 30, 50);
            color: #fff;
          }
        }
      }
    }
  }
  .keyword_tips {
    padding: 12px;
    font-size: .4rem;
    .tip_item {
      display: flex;
      justify-content: space-between;
      span, i {
        line-height: 3em;
      }
    }
    .tip_item+.tip_item {
      border-top: 1px solid #999;
    }
  }
}
</style>